<template>
  <div id="app">
	  <div id="content" class="content" @click="messageBoxTouch">
		  <message-box :userInfo="userInfo" @showLinkDetail="showLinkDetail" @feeback="feeback" v-for="(message,index) in messageList" :message="message" :key="index"></message-box>
      <div id="msg_end" style="height:20px; overflow:hidden"></div>
	  </div>
	  <foot-bar ref="footBar" :userInfo="userInfo" @editAreaBlur="editAreaBlur" @haha="messageBoxScrollToBottom" @inputFocus="inputFocus" @shurufaDone="shurufaDone" @emojiBarChange="emojiBarChange" @addMessage="addMessage"></foot-bar>
    <hr-dialog :visible="dialogVisble">
      <template slot="title">{{dialogInfo.FaqTitle}}</template>
      &nbsp;&nbsp;&nbsp;&nbsp;{{dialogInfo.FaqAnswer}}
      <template slot="foot">
        <div style="height:100%;" @click="dialogVisble = false">OK</div>
      </template>
    </hr-dialog>
  </div>
</template>

<script>
import messageBox from './components/messageBox.vue'
import FootBar from './components/footbar.vue'
import HrDialog from './components/hrDialog.vue'
import * as tool from "./utils/tool.js";
import toBottom from "./utils/toBottom.js";
import { setInterval } from 'timers';
// import { setTimeout, clearTimeout } from 'timers';

const baseUrl = process.env.NODE_ENV === 'production'?'https://oa.m.tencent.com/an:ntsapps_dev/mhrdeliverchat':'http://10.12.75.137'
// const baseUrl = process.env.NODE_ENV === 'production'?'http://10.12.75.137':'http://10.12.75.137'

export default {
  name: 'app',
  components: {
    messageBox,
    FootBar,
    HrDialog,
  },
	data(){
		return {
			chatInstance:null,
			messageList:[],
			dialogVisble:false,
			userInfo:{},
			dialogInfo:{},
			hookTimeOut:null,
            isFirstFocus:true,
            isAndroid:false,
            interval:null
		}
	},
	methods:{
		showLinkDetail(key) {
			this.$http.get(`/ChatService/UserPageMessage/GetFaqDetailInfo?key=${key}`).then(res=>{
				// console.log(res)
                this.dialogInfo = res.data
                this.dialogInfo.FaqAnswer = this.dialogInfo.FaqAnswer.replace(/\/an:ntsapps(_dev)?\/ts:/g,'http://')
				this.dialogVisble = true;
			})
		},
		feeback(key) {
			let postBody = {
				senderFullName: this.userInfo.EnglishName,
				toFullName: null,
				senderTime: tool.getTime(),
				content: [
				{
					type: "rtx_app_text_link",
					rtx_app_text_link: { "type": 1, "key": key },
					rtx_img: null,
					rtx_file: null,
					rtx_smiley: null
				}
				]
			}
			let _this = this
			this.$http.post('/ChatService/UserPageMessage/ClientSendMessage',postBody ).then(function(res) {
				// _this.hook() //点击是、否、人工客服的时候，也要hook一下
			});
		},
		emojiBarChange(show){
            let _this = this
            setTimeout(()=>{
                // toBottom(document)
                _this.toBottom()
            },200)
			// setTimeout(()=>{
			// 	if (show == true) {
			// 		//设置footbar的top值
			// 		let footbar = document.getElementById('footbar')
			// 		console.log('视窗高度：'+document.body.clientHeight);
			// 		footbar.style.top = (document.body.clientHeight-387)+'px'
			// 		console.log('top: '+footbar.style.top);
					
			// 		//设置content的height值
			// 		let content = document.getElementById('content')
			// 		console.log('视窗高度：'+document.body.clientHeight);
			// 		content.style.height = (document.body.clientHeight-387)+'px'
			// 		console.log('height: '+content.style.height);
			// 		this.messageBoxScrollToBottom()
			// 	}else {
			// 		//设置footbar的top值
			// 		let footbar = document.getElementById('footbar')
			// 		// footbar.style.top = (document.body.clientHeight-50)+'px'
			// 		console.log('top: '+footbar.style.top);
			// 		//设置content的height值
			// 		let content = document.getElementById('content')
			// 		content.style.height = (document.body.clientHeight-50)+'px'
			// 		console.log('height: '+content.style.height);

			// 	}
			// },400)
        },
        editAreaBlur() {
            //失焦的时候，恢复一下content的高度
            if(!this.isAndroid) {
                let viewHeight = document.body.clientHeight
                let content = document.getElementById('content')
                content.style.paddingTop = '0px'
                content.style.height = (viewHeight-50) +'px'
            }
        },
		inputFocus() {
            //只要聚焦了，就拉起了输入法，窗口大小被压缩，
            let _this = this
            let viewHeight = 0
            let hiddenHeight = 0
            let content = document.getElementById('content')
			setTimeout(()=>{
                if(_this.isAndroid) {
                    // viewHeight = document.body.clientHeight
                    // content.style.paddingTop ='0px'
                    // content.style.height = (viewHeight-50) +'px'
                }else {
                    viewHeight = document.body.clientHeight
                    hiddenHeight = document.body.scrollTop
                    content.style.paddingTop = hiddenHeight +'px'
                    content.style.height = (viewHeight-50) +'px'
                }
                // console.log(document.getElementById('footbar').style.bottom);
                // console.log(hiddenHeight);
                // console.log(content.style.paddingTop);
                // console.log(content.style.height);
                
                //把消息列表拉到最下面
                _this.toBottom()
			},700)
		},
		messageBoxScrollToBottom() {
            this.toBottom()
        },
        toBottom() {
            // toBottom(document)
            // setTimeout(()=>{
                // toBottom(document.getElementById('content'))
            // },200)
            document.getElementById('msg_end').scrollIntoView(false); 
            document.getElementById('footBarBottom').scrollIntoView(false)
            //  document.body.scrollTop = document.body.clientHeight
        },
		shurufaDone() {
			this.restore()
		},
		restore() {
			setTimeout(()=>{
				// alert('触摸消息列表时视窗高度：'+document.body.clientHeight);
				let footbar = document.getElementById('footbar')
				let viewHeight = document.body.clientHeight
				footbar.style.top = (viewHeight-50)+'px'
				//设置content的高度
				let content = document.getElementById('content')
				content.style.height = (viewHeight-50)+'px'

				//解决IOS下，触摸消息列表，输入框无法下移的问题....黑科技
				window.scrollTo(1, 1)
				window.scrollTo(0, 0)
			},150)
		},
		messageBoxTouch(){

            //暂时取消
            // return
            //让输入框失焦
			document.getElementById('editArea').blur()
            //把表情栏收起来
            this.$refs['footBar'].showEmojiBar(false)
            //黑科技
            window.scrollTo(1, 1)
            window.scrollTo(0, 0)
		},
		// hook() {
		// 	//hook模式，开启延迟器
		// 	let _this = this
		// 	this.hookTimeOut = setTimeout(()=>{
		// 		_this.getHistoryMessage()
		// 	},1000)
		// },
		addMessage(messageObj) {
			// this.hook()
			console.log('用户发送消息：');
			console.log(messageObj);
			
            this.messageList.push(messageObj)
            let _this = this
            setTimeout(()=>{
                _this.toBottom()
            },200)
		},
		getUserInfo() {
			let _this = this
			//获取表情配置，获取一次放本地
			// axios.post('/ChatService/UserPageMessage/GetChatExpression',{}).then(function(res) {
			//     let haha = ''
			//     res.data.forEach(item=>{
			//       haha += JSON.stringify(item)+',\n'
			//     })
			//     console.log(haha);
				
			// });
			this.$http.get('/ChatService/UserPageMessage/GetStaffInfo').then(res=> {
                this.userInfo = res.data
				this.connect() //这个地方因为axios是单独引入的，所以this指向是axios实例
			},rej=>{
                window.location.reload(true)
            });
        },
        connect() {
            //先告诉后端，我是谁
            this.$http.get(`/ChatService/UserPageMessage/ClientConnected?userName=${this.userInfo.EnglishName}`).then(res=>{
                //拉取历史消息
                this.getHistoryMessage()
            },rej=>{
                window.location.reload(true)
            })
        },
		getHistoryMessage() {
			this.$http.get(`/ChatService/UserPageMessage/GetHistoryInfo?userName=${this.userInfo.EnglishName}`).then(res=>{
				console.log('signalr历史消息：')
				console.log(res);
				let historyList = res.data ==''?[]:res.data
				let currUserName = this.userInfo.FullName
				console.log(this.userInfo);
				
				this.messageList = []	//先清空历史消息
				historyList.forEach(message=>{
					if(message.senderFullName == currUserName) {
						this.messageList.push({
							isClient:true,
							...message
						})
					}else {
						this.messageList.push(message)
					}
                })
			    let _this = this
                setTimeout(()=>{
                    _this.toBottom()
				},500)
				
				//开启轮询
                this.polling()
			},rej=>{
                window.location.reload(true)
            })
        },
        polling(){
            let _this = this
            clearInterval(this.interval)
            this.interval = setInterval(()=>{
                _this.$http.get(`/ChatService/UserPageMessage/ClientReceiveMessage?userName=${this.userInfo.EnglishName}`).then(res=>{
                    if (res.data != 'null'&& res.data != '') {
                        console.log('轮询获取到消息');
                        console.log(res.data);
                        
                        _this.messageList.push(res.data)
                        // setTimeout(()=>{
                            _this.$nextTick(()=>{
                                _this.toBottom()
                            })
                        // },2000)
                    }
                })
            },1000)
            
        },
		// connect() {
		// 	let _this = this
		// 	var connection = $.hubConnection()
		// 	connection.url = `${baseUrl}/ChatService/signalr`
		// 	var proxy = connection.createHubProxy("MyHub")

		// 	//把connection打开
		// 	connection.start({ jsonp: true }).done(function () {
		// 		console.log("连接成功")
		// 		proxy.invoke("clientConnected", _this.userInfo.EnglishName);
		// 		//获取历史消息
		// 		_this.getHistoryMessage()
		// 	}).fail(function (reason) {
		// 		alert("SignalR connection failed: " + reason)
		// 	})
			
		// 	//获取signalr消息
		// 	proxy.on("clientReceiveMessage", function (msg) {
		// 		console.log('signalr消息：')
		// 		console.log(JSON.parse(msg))
        //         _this.messageList.push(JSON.parse(msg))//后端给的是字符串，坑爹，转换一下
        //         //把消息列表拉到底部
        //         setTimeout(()=>{
        //             _this.toBottom()
        //         },200)
				
		// 		//清除定时器
		// 		clearTimeout(_this.hookTimeOut)
		// 	})
        // },
        is_weixin() {
            var u = navigator.userAgent, app = navigator.appVersion;
            if (u.indexOf('Android') > -1 || u.indexOf('Linux') > -1) {
                this.isAndroid = true
                console.log("这是安卓");
            }else {
                console.log("这是苹果");
            }
        }
	},
	mounted() {
        this.is_weixin()
		this.getUserInfo()
		// console.log('视窗高度：'+document.body.clientHeight);
		
	}
}
</script>

<style lang="scss" scoped>
#app {
  position: relative;
//   display: flex;
//   flex-direction: column;
  height: 100%;
	// overflow: hidden;
  background-color: #EBEBEB;
//   background-color: green;
//   background-image: url('./assets/bg.png');
  .content{
    //   position: absolute;
    //   top: 0px;
    // flex-grow: 1;
        // padding-bottom: 20px;
		// background-color: yellow;
	background-color: #EBEBEB;
	height: calc(100% - 50px);
    overflow-y: scroll;
  }
}
</style>
